package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("EventqualitytypeRestController")
public class EventqualitytypeRestController extends CmiEmaController {

	/**
	 * Create a new Eventqualitytype entity
	 * 
	 */
	@RequestMapping(value = "/newEventqualitytype", method = RequestMethod.POST)
	@ResponseBody
	public Object newEventqualitytype(@RequestBody Eventqualitytype eventqualitytype) {
		eventqualitytypeService.saveEventqualitytype(eventqualitytype);
		return JSONObject.parse(cmiPsonService
				.toJsonString(eventqualitytypeDAO.findEventqualitytypeByPrimaryKey(eventqualitytype.getId()), 2));
	}

	@RequestMapping(value = "/restNewEventqualitytype", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewEventqualitytype(@RequestBody String eventqualitytypeJson) {
		Eventqualitytype eventqualitytype = new Gson().fromJson(eventqualitytypeJson, Eventqualitytype.class);
		appendReferences(eventqualitytype);
		eventqualitytypeService.saveEventqualitytype(eventqualitytype);
		return JSONObject.parse(cmiPsonService
				.toJsonString(eventqualitytypeDAO.findEventqualitytypeByPrimaryKey(eventqualitytype.getId()), 2));
	}

	@RequestMapping(value = "/saveEventqualitytype", method = RequestMethod.PUT)
	@ResponseBody
	public Eventqualitytype saveEventqualitytype(@RequestBody Eventqualitytype eventqualitytype) {
		eventqualitytypeService.saveEventqualitytype(eventqualitytype);
		return eventqualitytypeDAO.findEventqualitytypeByPrimaryKey(eventqualitytype.getId());
	}

	@RequestMapping(value = "/restSaveEventqualitytype", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveEventqualitytype(@RequestBody String eventqualitytypeJson) {
		Eventqualitytype eventqualitytype = new Gson().fromJson(eventqualitytypeJson, Eventqualitytype.class);
		appendReferences(eventqualitytype);
		CmiPsonService cmiPsonService = new CmiPsonService();
		eventqualitytypeService.saveEventqualitytype(eventqualitytype);
		return JSONObject.parse(cmiPsonService
				.toJsonString(eventqualitytypeDAO.findEventqualitytypeByPrimaryKey(eventqualitytype.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteEventqualitytype/{eventqualitytypeId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteEventqualitytype(@PathVariable Integer eventqualitytypeId) {
		Eventqualitytype eventqualitytype = eventqualitytypeDAO.findEventqualitytypeByPrimaryKey(eventqualitytypeId);
		eventqualitytypeService.deleteEventqualitytype(eventqualitytype);
	}

	@RequestMapping(value = "/restConfirmDeleteEventqualitytypes")
	@ResponseBody
	public Object restConfirmDeleteEventqualitytypes(@RequestBody Set<Integer> deleteEventqualitytypesIds) {
		Set<Eventqualitytype> deleteEventqualitytypes = eventqualitytypeDAO
				.findEventqualitytypesByIds(deleteEventqualitytypesIds);
		Set<Eventqualitytype> referencedEventqualitytypes = eventqualitytypeService
				.loadReferenceEventqualitytypes(deleteEventqualitytypes);
		deleteEventqualitytypes.removeAll(referencedEventqualitytypes);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedEventqualitytypes);
		jsonObject.put("deleteEntitys", deleteEventqualitytypes);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteEventqualitytypes")
	@ResponseBody
	public Object restDeleteEventqualitytypes(@RequestBody Set<Eventqualitytype> deleteEventqualitytypes) {
		Iterator<Eventqualitytype> iterator = deleteEventqualitytypes.iterator();
		while (iterator.hasNext()) {
			Eventqualitytype currentEventqualitytype = iterator.next();
			eventqualitytypeService.deleteEventqualitytype(currentEventqualitytype);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listEventqualitytypes");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadEventqualitytype/{eventqualitytypeId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventqualitytype(@PathVariable Integer eventqualitytypeId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(eventqualitytypeDAO.findEventqualitytypeByPrimaryKey(eventqualitytypeId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventqualitytypeEvent/{eventqualitytypeId}/event", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventqualitytypeEvent(@PathVariable Integer eventqualitytypeId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				eventqualitytypeDAO.findEventqualitytypeByPrimaryKey(eventqualitytypeId).getEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventqualitytypeQualitytype/{eventqualitytypeId}/qualitytype", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventqualitytypeQualitytype(@PathVariable Integer eventqualitytypeId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				eventqualitytypeDAO.findEventqualitytypeByPrimaryKey(eventqualitytypeId).getQualitytype(), 2,
				cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	public void appendReferences(Eventqualitytype eventqualitytype) {

		Event event = eventqualitytype.getEvent();
		if (event != null)
			eventqualitytype.setEvent(eventService.findEventByPrimaryKey(event.getId()));

		Qualitytype qualitytype = eventqualitytype.getQualitytype();
		if (qualitytype != null)
			eventqualitytype.setQualitytype(qualitytypeService.findQualitytypeByPrimaryKey(qualitytype.getId()));

	}

	@RequestMapping(value = "/restGetEventqualitytypeEvent/{eventqualitytypeId}/event", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventqualitytypeEvent(@PathVariable Integer eventqualitytypeId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				eventqualitytypeDAO.findEventqualitytypeByPrimaryKey(eventqualitytypeId).getEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventqualitytypeQualitytype/{eventqualitytypeId}/qualitytype", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventqualitytypeQualitytype(@PathVariable Integer eventqualitytypeId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				eventqualitytypeDAO.findEventqualitytypeByPrimaryKey(eventqualitytypeId).getQualitytype(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restListEventqualitytypes", method = RequestMethod.GET)
	@ResponseBody
	public Object restListEventqualitytypes() {
		return JSONObject.parse(cmiPsonService.toJsonString(eventqualitytypeService.loadEventqualitytypes(), 2));
	}

	@RequestMapping(value = "/restListEventqualitytypesPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListEventqualitytypesPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = eventqualitytypePaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Eventqualitytype> eventqualitytypes = eventqualitytypeDAO.findAllEventqualitytypes(startResult,
				cmiPagination.getPaginationSize());
		String eventqualitytypeString = cmiPsonService.toPsonString(eventqualitytypes, 2, cmiPagination);

		return JSONObject.parse(eventqualitytypeString);
	}

	@RequestMapping("/eventqualitytypeSelectBox")
	@ResponseBody
	public JSONObject eventqualitytypeSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Event":
				entitySet = eventService.loadEventsByIdSet(searchValue);
				break;
			case "Qualitytype":
				entitySet = qualitytypeService.loadQualitytypesByIdSet(searchValue);
				break;

			// 被引用键
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Event":
				entitySet = eventDAO.findAllEvents((pageNumber - 1) * paginationSize, paginationSize);
				count = eventService.countEvents();
				break;
			case "Qualitytype":
				entitySet = qualitytypeDAO.findAllQualitytypes((pageNumber - 1) * paginationSize, paginationSize);
				count = qualitytypeService.countQualitytypes();
				break;

			// 被引用键
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Event":
				entitySet = eventDAO.findEventByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventService.countEventsByName(queryword);
				break;
			case "Qualitytype":
				entitySet = qualitytypeDAO.findQualitytypeByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = qualitytypeService.countQualitytypesByName(queryword);
				break;

			// 被引用键
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
